package com.foreveross.taskservice.taskcache.redis.util;

import org.apache.log4j.Logger;
import org.dayatang.domain.InstanceFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * 一个最简易的工具
 * 支持获取连接和释放
 * @author Administrator
 *
 */
public class JedisUtil {
	
	private static JedisPool pool;
	private static Logger log=Logger.getLogger(JedisUtil.class);
	
	
	private static synchronized void initPool(){
		if(pool==null){
			pool=(JedisPool) InstanceFactory.getInstance(JedisPool.class, "jedisPool");
		}
	}
	private static void validatePool(){
		if(pool==null){
			initPool();
		}
	}
	
	public  static Jedis getResource(){
		validatePool();
		return pool.getResource();
	}
	/**
	 * 释放连接
	 * @param jedis
	 */
	public static void returnResource(Jedis jedis){
		validatePool();
		if(jedis!=null){//归还池里验证无效，null也可以回收，我们自己需要把握
			jedis.unwatch();//回收的时候如果之前使用过watch命令而没有释放或者提交事务可能会导致后续业务的提交
			pool.returnResource(jedis);
		}else{
			log.warn("回收redis null");
		}
	}
	/**
	 * 销毁连接
	 * @param jedis
	 */
	public static void returnBrokenResource(Jedis jedis){
		validatePool();
		if(jedis!=null){
			pool.returnBrokenResource(jedis);//消灭此连接
		}else{
			log.warn("销毁redis null");
		}
	}
	
}
